package com.example.demo2022.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo2022.common.web.WebResultJson;
import com.example.demo2022.entity.User;
import com.example.demo2022.service.ILoginLogService;
import com.example.demo2022.service.IMenuService;
import com.example.demo2022.service.IUserService;
import com.example.demo2022.util.TokenUtil;
import com.example.demo2022.vo.UserRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/************************************
 * @PACKAGE : com.example.demo2022.controller
 * @Author    :  叫我老伯
 * @Date    : 2022/5/30 21:53
 * @Desc    : 测试返回值
 ***********************************/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ILoginLogService loginLogService;

    @Autowired
    private IMenuService menuService;

    @RequestMapping("/listAll")
    public WebResultJson listAll() {
        return WebResultJson.ok(userService.list());
    }

    @RequestMapping("/add")
    public WebResultJson add(User user) {
        return WebResultJson.ok(userService.save(user));
    }

    @RequestMapping(value = "/login",method = {RequestMethod.GET,RequestMethod.POST})
    public WebResultJson login(User user){
        if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword()) ){
            return WebResultJson.fail("用户或者密码为空！");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername())
                .eq("password",user.getPassword());
        User userDb = userService.getOne(queryWrapper);
        if(userDb != null){
            // 获取用户所有的权限信息
            Set<String> menuUrlList = menuService.listUrlByUserId(userDb.getId());
            userDb.setMenuUrlList(menuUrlList);
            // 登陆成功了
            String token = TokenUtil.generateToken(userDb);
            userDb.setToken(token);
            loginLogService.saveLoginLog(userDb.getId());
            return WebResultJson.ok(userDb);
        }else{
            return WebResultJson.fail("用户名或密码错误！");
        }

    }

    /**
     * 更新用户信息，修改用户和角色的关联表
     *  1、多对多关联表的更新
     *  2、复杂参数的传递
     */
    @RequestMapping("/updateUserRoles")
    public WebResultJson updateUserRoles(@RequestBody UserRoleVo userRoleVo){

        userService.updateUserRoles(userRoleVo);

        return WebResultJson.ok();
    }

}
